package com.yihu.wlyy.web.doctor.talk;

import java.util.*;

import com.yihu.wlyy.entity.*;
import com.yihu.wlyy.entity.doctor.Doctor;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.service.common.account.PatientService;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yihu.wlyy.service.app.talk.TalkGroupService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.web.BaseController;

@Controller
@RequestMapping(value = "/doctor/talkgroup")
public class DoctorTalkGroupController extends BaseController {
	// 医生服务类
	@Autowired
	private DoctorService doctorService;
	@Autowired
	// 讨论组服务类
	private TalkGroupService talkGroupService;
    @Autowired
	private PatientService patientService;

	/**
	 * 医生创建讨论组
	 * 
	 * @param name 讨论组名称
	 * @param type 讨论组类型
	 * @param talkDoctor 讨论组医生
	 * @param talkDoctorName 讨论组医生名称
	 * @param doctorType 成员医生类型
	 * @param patient 病人标识
	 * @param patientName 病人姓名
	 * @param patientInclude 病人是否加入讨论组
	 * @return
	 */
	@RequestMapping(value = "/create")
	@ResponseBody
	public String createTalkGroup(
			@RequestParam(required = true)String name,
			@RequestParam(required = true)int type,
			@RequestParam(required = true)String talkDoctor,
			@RequestParam(required = true)String talkDoctorName,
			@RequestParam(required = true)int doctorType,
			@RequestParam(required = false)String patient,
			@RequestParam(required = false)String patientName,
			@RequestParam(required = false)String patientInclude){
		try{
			Doctor doctor = doctorService.findDoctorByCode(getUID());
			List<WlyyTalkGroupMember> members = new ArrayList<WlyyTalkGroupMember>();
			
			if(doctor != null){
				//讨论组建立
				WlyyTalkGroup talkGroup = new WlyyTalkGroup();
				
				if(StringUtils.isEmpty(name)){
					return error(-1,"请输入讨论组名称");
				}
				if(StringUtils.isEmpty(talkDoctor)){
					return error(-1,"请输入讨论组成员医生");
				}
				if(StringUtils.isEmpty(talkDoctorName)){
					return error(-1,"请输入讨论组成员医生姓名");
				}
				// 讨论组针对某一病人时
				if(type == 1){
					if(StringUtils.isEmpty(patient)){
						return error(-1,"请输入患者标识");
					}
					if(StringUtils.isEmpty(patientName)){
						return error(-1,"请输入患者姓名");
					}
					if(StringUtils.isEmpty(patientInclude)){
						return error(-1,"请输入患者是否加入讨论组");
					}
				}
				
				talkGroup.setCode(talkGroupService.getCode());
				talkGroup.setName(name);
				talkGroup.setType(type);
				talkGroup.setCreator(doctor.getCode());
				talkGroup.setCreatorName(doctor.getName());
				talkGroup.setHospitalCode(doctor.getHospital());
				talkGroup.setHospitalName(doctor.getHosptialName());
				talkGroup.setPatient(patient);
				talkGroup.setPatientName(patientName);
				talkGroup.setCzrq(new Date());
				
				//病人加入讨论组
				if(!StringUtils.isEmpty(patientInclude) && patientInclude.equals("1")){
					WlyyTalkGroupMember patientMember = new WlyyTalkGroupMember();
					
					patientMember.setMemberCode(patient);
					patientMember.setMemberName(patientName);
					patientMember.setGroupCode(talkGroup.getCode());
					patientMember.setGroupName(name);
					patientMember.setType(4);
					patientMember.setStatus(1);
					patientMember.setCzrq(new Date());
					
					members.add(patientMember);
				}
				
				//当前医生加入讨论组
				WlyyTalkGroupMember doctorMember = new WlyyTalkGroupMember();
				
				doctorMember.setMemberCode(doctor.getCode());
				doctorMember.setMemberName(doctor.getName());
				doctorMember.setGroupCode(talkGroup.getCode());
				doctorMember.setGroupName(name);
				doctorMember.setType(doctor.getLevel());
				doctorMember.setStatus(1);
				doctorMember.setCzrq(new Date());	
				members.add(doctorMember);
				
				//指定的讨论组另一医生成员
				WlyyTalkGroupMember doctorTalkMember = new WlyyTalkGroupMember();
				
				doctorTalkMember.setMemberCode(talkDoctor);
				doctorTalkMember.setMemberName(talkDoctorName);
				doctorTalkMember.setGroupCode(talkGroup.getCode());
				doctorTalkMember.setGroupName(name);
				doctorTalkMember.setType(doctorType);
				doctorTalkMember.setStatus(1);
				doctorTalkMember.setCzrq(new Date());	
				members.add(doctorTalkMember);
				
				talkGroupService.saveTalkGroup(talkGroup, members);
				
				JSONObject jsonObject = new JSONObject(talkGroup);
                JSONArray membersJson = new JSONArray();

				for(WlyyTalkGroupMember member : members){
					JSONObject memberJson = new JSONObject(member);
					if(member.getType() == 4){
						Patient p = patientService.findByCode(member.getMemberCode());

						if(p != null){
							memberJson.put("photo",p.getPhoto());
							memberJson.put("sex",p.getSex());
						}
					}else{
						Doctor d = doctorService.findDoctorByCode(member.getMemberCode());

						if(d != null){
							memberJson.put("photo",d.getPhoto());
							memberJson.put("sex",d.getSex());
						}
					}
					membersJson.put(memberJson);
				}

				jsonObject.put("members", membersJson);
				
				return write(200, "创建讨论组成功!","data",jsonObject);
			}else{
				return error(-1, "创建讨论组失败!");
			}
		
		}catch(Exception e){
			return error(-1, "创建讨论组失败!");
		}
	}

	/**
	 * 创建讨论组
	 *
	 * @param name 讨论组名称
	 * @param type 讨论组类型
	 * @param members 讨论组成员 [{"doctor":"xxx","doctorName":"xxx","doctorType":1}]
	 * @param patient 患者
	 * @param patientName 患者姓名
	 * @param patientInclude 患者是否加入
	 * @return
	 */
	@RequestMapping(value = "/create/members")
	@ResponseBody
	public String createTalkGroupMany(@RequestParam(required = true)String name,
									  @RequestParam(required = true)int type,
									  @RequestParam(required = true)String members,
									  @RequestParam(required = false)String patient,
									  @RequestParam(required = false)String patientName,
									  @RequestParam(required = false)String patientInclude){
		try{
			Doctor doctor = doctorService.findDoctorByCode(getUID());
			List<WlyyTalkGroupMember> talkMembers = new ArrayList<WlyyTalkGroupMember>();

			if(doctor != null){
				//讨论组建立
				WlyyTalkGroup talkGroup = new WlyyTalkGroup();

				if(StringUtils.isEmpty(name)){
					return error(-1,"请输入讨论组名称");
				}
				if(StringUtils.isEmpty(members)){
					return error(-1,"讨论组成员不能为空");
				}
				// 讨论组针对某一病人时
				if(type == 1){
					if(StringUtils.isEmpty(patient)){
						return error(-1,"请输入患者标识");
					}
					if(StringUtils.isEmpty(patientName)){
						return error(-1,"请输入患者姓名");
					}
					if(StringUtils.isEmpty(patientInclude)){
						return error(-1,"请输入患者是否加入讨论组");
					}
				}

				talkGroup.setCode(talkGroupService.getCode());
				talkGroup.setName(name);
				talkGroup.setType(type);
				talkGroup.setCreator(doctor.getCode());
				talkGroup.setCreatorName(doctor.getName());
				talkGroup.setHospitalCode(doctor.getHospital());
				talkGroup.setHospitalName(doctor.getHosptialName());
				talkGroup.setPatient(patient);
				talkGroup.setPatientName(patientName);
				talkGroup.setCzrq(new Date());

				//病人加入讨论组
				if(!StringUtils.isEmpty(patientInclude) && patientInclude.equals("1")){
					WlyyTalkGroupMember patientMember = new WlyyTalkGroupMember();

					patientMember.setMemberCode(patient);
					patientMember.setMemberName(patientName);
					patientMember.setGroupCode(talkGroup.getCode());
					patientMember.setGroupName(name);
					patientMember.setType(4);
					patientMember.setStatus(1);
					patientMember.setCzrq(new Date());

					talkMembers.add(patientMember);
				}

				//当前医生加入讨论组
				WlyyTalkGroupMember doctorMember = new WlyyTalkGroupMember();

				doctorMember.setMemberCode(doctor.getCode());
				doctorMember.setMemberName(doctor.getName());
				doctorMember.setGroupCode(talkGroup.getCode());
				doctorMember.setGroupName(name);
				doctorMember.setType(doctor.getLevel());
				doctorMember.setStatus(1);
				doctorMember.setCzrq(new Date());
				talkMembers.add(doctorMember);

				JSONArray membersJArray = new JSONArray(members);

				if(membersJArray != null){
					for(int i = 0; i < membersJArray.length(); i++){
						JSONObject object = membersJArray.getJSONObject(i);
						//指定的讨论组另一医生成员
						WlyyTalkGroupMember doctorTalkMember = new WlyyTalkGroupMember();

						doctorTalkMember.setMemberCode(object.getString("doctor"));
						doctorTalkMember.setMemberName(object.getString("doctorName"));
						doctorTalkMember.setGroupCode(talkGroup.getCode());
						doctorTalkMember.setGroupName(name);
						doctorTalkMember.setType(object.getInt("doctorType"));
						doctorTalkMember.setStatus(1);
						doctorTalkMember.setCzrq(new Date());

						talkMembers.add(doctorTalkMember);
					}
				}

				talkGroupService.saveTalkGroup(talkGroup, talkMembers);

				JSONObject jsonObject = new JSONObject(talkGroup);
				JSONArray membersJson = new JSONArray();

				for(WlyyTalkGroupMember member : talkMembers){
					JSONObject memberJson = new JSONObject(member);
					if(member.getType() == 4){
						Patient p = patientService.findByCode(member.getMemberCode());

						if(p != null){
							memberJson.put("photo",p.getPhoto());
							memberJson.put("sex",p.getSex());
						}
					}else{
						Doctor d = doctorService.findDoctorByCode(member.getMemberCode());

						if(d != null){
							memberJson.put("photo",d.getPhoto());
							memberJson.put("sex",d.getSex());
						}
					}
					membersJson.put(memberJson);
				}

				jsonObject.put("members", membersJson);

				return write(200, "创建讨论组成功!","data",jsonObject);
			}else{
				return error(-1, "创建讨论组失败!");
			}
		}catch (Exception e){
			e.printStackTrace();
			return error(-1,"创建讨论组失败");
		}
	}

	/**
	 * 添加讨论组成员
	 * 
	 * @param groupCode 讨论组标识
	 * @param groupName 讨论组名称
	 * @param doctor 添加医生
	 * @param doctorName 添加医生姓名
	 * @param doctorType 医生类型
	 * @return
	 */
	@RequestMapping(value = "addmember")
	@ResponseBody
	public String addTalkMember(
			@RequestParam(required = true)String groupCode,
			@RequestParam(required = true)String groupName,
			@RequestParam(required = true)String doctor,
			@RequestParam(required = true)String doctorName,int doctorType){
		try{
			WlyyTalkGroupMember member = new WlyyTalkGroupMember();
			
			member.setGroupCode(groupCode);
			member.setGroupName(groupName);
			member.setMemberCode(doctor);
			member.setMemberName(doctorName);
			member.setStatus(1);
			member.setCzrq(new Date());
			member.setType(doctorType);
			
			talkGroupService.saveTalkMember(member);

			JSONObject memberJson = new JSONObject(member);

			if(member.getType() == 4){
				Patient p = patientService.findByCode(member.getMemberCode());

				if(p != null){
					memberJson.put("photo",p.getPhoto());
					memberJson.put("sex",p.getSex());
				}
			}else{
				Doctor d = doctorService.findDoctorByCode(member.getMemberCode());

				if(d != null){
					memberJson.put("photo",d.getPhoto());
					memberJson.put("sex",d.getSex());
				}
			}
			
			return write(200, "添加讨论组成员成功!","data",memberJson);
		}catch(Exception e){
			return error(-1, "添加讨论组成员失败!");
		}
	}


	/**
	 * 添加成员
	 *
	 * @param groupCode 分组code
	 * @param members 讨论组成员[{"doctor":"xxx","doctorName":"xxx","doctorType":1}]
	 * @return
	 */
	@RequestMapping(value = "/addmembers")
	@ResponseBody
	public String addMembers(String groupCode,String groupName,String members){
		try{
			List<WlyyTalkGroupMember> talkMembers = new ArrayList<>();
			JSONArray membersJArray = new JSONArray(members);
			WlyyTalkGroup talkGroup = talkGroupService.findTalkGroup(groupCode);

			if(talkGroup == null){
				throw new Exception("讨论组不存在");
			}

			if(membersJArray != null){
				for(int i = 0; i < membersJArray.length(); i++){
					JSONObject object = membersJArray.getJSONObject(i);
					//指定的讨论组另一医生成员
					WlyyTalkGroupMember doctorTalkMember = new WlyyTalkGroupMember();

					doctorTalkMember.setMemberCode(object.getString("doctor"));
					doctorTalkMember.setMemberName(object.getString("doctorName"));
					doctorTalkMember.setGroupCode(groupCode);
					doctorTalkMember.setGroupName(talkGroup.getName());
					doctorTalkMember.setType(object.getInt("doctorType"));
					doctorTalkMember.setStatus(1);
					doctorTalkMember.setCzrq(new Date());

					talkMembers.add(doctorTalkMember);
				}
			}

			talkGroupService.saveMembers(talkMembers);

			JSONObject jsonObject = new JSONObject(talkGroup);
			JSONArray membersJson = new JSONArray();

			for(WlyyTalkGroupMember member : talkMembers){
				JSONObject memberJson = new JSONObject(member);
				if(member.getType() == 4){
					Patient p = patientService.findByCode(member.getMemberCode());

					if(p != null){
						memberJson.put("photo",p.getPhoto());
						memberJson.put("sex",p.getSex());
					}
				}else{
					Doctor d = doctorService.findDoctorByCode(member.getMemberCode());

					if(d != null){
						memberJson.put("photo",d.getPhoto());
						memberJson.put("sex",d.getSex());
					}
				}
				membersJson.put(memberJson);
			}

			jsonObject.put("members", membersJson);

			return write(200,"添加成员成功");
		}catch (Exception e){
			e.printStackTrace();
			return error(-1,"添加成员失败!");
		}
	}


    /**
     * 移除讨论组成员
     * 
     * @param groupCode 讨论组标识
     * @param memberCode 讨论组成员标识
     * @return
     */
	@RequestMapping(value = "removemember")
	@ResponseBody
	public String removeTalkMember(
			@RequestParam(required = true)String groupCode,
			@RequestParam(required = true)String memberCode){
		try{
			talkGroupService.deleteTalkMember(groupCode, memberCode);
			return write(200, "移除成员成功!");
		}catch(Exception e){
			return error(-1, "移除讨论组成员失败!");
		}
	}

	/**
	 * 移除成员
	 *
	 * @param groupCode
	 * @param members
	 * @return
	 */
	@RequestMapping(value = "/removemembers")
	@ResponseBody
	public String removeMembers(String groupCode,String members){
		try{
			String[] memberArray = members.split(",");
			for(String member : memberArray){
				talkGroupService.deleteTalkMember(groupCode, member);
			}
			return write(200,"移除成员成功");
		}catch (Exception e){
			e.printStackTrace();
			return error(-1,"移除成员失败!");
		}
	}

	/**
	 * 获取医生讨论组
	 * 
	 * @return
	 */
	@RequestMapping(value = "mytalkgroups")
	@ResponseBody
	public String getMyTalkGroup(
			@RequestParam(required = false)String doctorName,
			@RequestParam(required = false)String groupType){
		try{
			JSONArray jsonArray = new JSONArray();
			Set<String> typeSet = new HashSet<>();

			if(!StringUtils.isEmpty(groupType)) {
				for (String type : groupType.split(",")) {
					typeSet.add(type);
				}
			}

			List<WlyyTalkGroup> groups = new ArrayList<>();

			if(!StringUtils.isEmpty(doctorName)){
				groups = talkGroupService.searchTalkGroupsByDoctorName(getUID(),doctorName);
			}
			else{
				groups = talkGroupService.findDoctorTalkGroups(getUID());
			}

			if(typeSet.size() > 0 && groups != null){
				for(WlyyTalkGroup talk : groups){
					if(!StringUtils.isEmpty(String.valueOf(talk.getType())) && typeSet.contains(String.valueOf(talk.getType()))){
						jsonArray.put(new JSONObject(talk));
					}
				}
			}else if(groups != null){
				jsonArray.put(new JSONArray(groups));
			}

			return write(200, "获取医生讨论组成功!","data",jsonArray);
		}catch(Exception ex){
			return error(-1, "获取医生讨论组列表失败!");
		}
	}


	/**
	 * 查询讨论组签约量
	 *
	 * @param groups
	 * @return
	 */
	@RequestMapping(value = "/group_sign")
	@ResponseBody
	public String getMyTalkGroupSign(String groups){
		try{
			List<Map<String,Object>> data = talkGroupService.getTalkGroupsSing(groups.split(","));

			return write(200,"查询成功","data",new JSONArray(data));
		}catch (Exception e){
			return error(-1,"查询失败");
		}
	}

	/**
	 * 获取讨论组成员列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "groupmembers")
	@ResponseBody
	public String getTalkGroupMembers(@RequestParam(required = true)String groupCode){
		try{
			JSONArray result = new JSONArray();
			List<WlyyTalkGroupMember> groupMembers = talkGroupService.findTalkGroupMembers(groupCode);

			if(groupMembers == null){
				groupMembers = new ArrayList<>();
			}

			for(WlyyTalkGroupMember member : groupMembers){
				JSONObject memberJson = new JSONObject(member);
				if(member.getType() == 4){
					Patient p = patientService.findByCode(member.getMemberCode());

					if(p != null){
						memberJson.put("photo",p.getPhoto());
						memberJson.put("sex",p.getSex());
					}
				}else{
                    Doctor doctor = doctorService.findDoctorByCode(member.getMemberCode());

					if(doctor != null){
						memberJson.put("photo",doctor.getPhoto());
						memberJson.put("sex",doctor.getSex());
					}
				}
				result.put(memberJson);
			}
			
			return write(200, "获取讨论组成员列表成功!","data",result);
		}catch(Exception ex){
			return error(-1, "获取讨论组成员列表失败!");
		}
	}

	/**
	 * 获取医生针对某个患者讨论组历史记录
	 * 
	 * @param patient
	 * @return
	 */
	@RequestMapping(value = "histories")
	@ResponseBody
    public String getTalkGroupHistory(@RequestParam(required = true)String patient){
    	try{
    		JSONArray groups = talkGroupService.getTalkGroupHistories(getUID(),patient);
    		return write(200, "获取讨论组历史记录成功!","data",groups);
    	}catch(Exception e){
    		return error(-1, "获取讨论组历史记录失败!");
    	}
    }

	/**
	 * 查找与当前医生相关成员的讨论组
	 *
	 * @param member
	 * @return
     */
	@RequestMapping(value = "related")
	@ResponseBody
    public String getTalkGroupRelated(@RequestParam(required = true)String member,@RequestParam(required = false)String groupType){
    	try{
			JSONArray jsonArray = new JSONArray();
			Set<String> typeSet = new HashSet<>();

			if(!StringUtils.isEmpty(groupType)) {
				for (String type : groupType.split(",")) {
					typeSet.add(type);
				}
			}

			List<WlyyTalkGroup> groups = talkGroupService.getTalkGroupRelated(getUID(),member);

			if(typeSet.size() > 0 && groups != null){
				for(WlyyTalkGroup talk : groups){
					if(!StringUtils.isEmpty(String.valueOf(talk.getType())) && typeSet.contains(String.valueOf(talk.getType()))){
						jsonArray.put(new JSONObject(talk));
					}
				}
			}else if(groups != null){
				jsonArray.put(new JSONArray(groups));
			}

    		return write(200,"查询成功!","data",jsonArray);
		}catch (Exception e){
			return error(-1,"查询失败!");
		}
	}

	/**
	 * 查询医生讨论组数量
	 *
	 * @return
	 */
	@RequestMapping(value = "count")
	@ResponseBody
	public String getMyTalkGroupCount(){
		try{
			long  count = talkGroupService.getDoctorTalkGroupCount(getUID());

			return write(200,"查询成功!","data",count);
		}catch (Exception e){
			return error(-1,"查询失败!");
		}
	}

}
